package com.sherlockHolmes.init.base.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sherlockHolmes.init.base.config.ImgMapConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class FileUtils {
    public static String upload(MultipartFile file) throws IOException {
        if(file.isEmpty()){
            throw new RuntimeException("文件不存在");
        }
        String originalFilename = file.getOriginalFilename();
        if(originalFilename==null){
            throw new RuntimeException("文件不存在");
        }
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //设置新文件名
        String newFileName = System.currentTimeMillis()+Uid.getUid()+suffix;
        //将文件转成base64
        String encode = Base64.encode(file.getBytes());
        //设置转存到Gitee仓库参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("access_token", ImgMapConfig.ACCESS_TOKEN);
        paramMap.put("message", ImgMapConfig.ADD_MESSAGE);
        paramMap.put("content", encode);
        //转存文件路径
        String targetDir = ImgMapConfig.PATH + newFileName;
        //设置请求路径
        String requestUrl = String.format(ImgMapConfig.CREATE_REPOS_URL, ImgMapConfig.OWNER,
                ImgMapConfig.REPO_NAME, targetDir);
        log.info("上传文件到Gitee仓库，请求路径：{}", requestUrl);
        String resultJson = HttpUtil.post(requestUrl, paramMap);
        JSONObject jsonObject = JSONUtil.parseObj(resultJson);
        //表示操作失败
        if (jsonObject==null || jsonObject.getObj("commit") == null) {
            throw new RuntimeException("文件上传失败");
        }
        JSONObject content = JSONUtil.parseObj(jsonObject.getObj("content"));
        //https://gitee.com/zhugekongming1/img/blob/master/imgs/Tue%20Nov%2007%2021:01:10%20CST%202023/16993620707953913f3e8-2b3f-4d4c-af39-5736adb55c501699362070796.jpg
        String downloadUrl = content.getStr("download_url");
        Object html_url = content.getObj("html_url");
//        log.info("上传成功，访问地址：{}",(String) html_url);
        log.info("上传成功，下载地址：{}", downloadUrl);
        return downloadUrl;
    }
    /**
     * 删除文件
     */
    public static boolean deleteFile(String filePath){
        if(filePath==null || "".equals(filePath.trim())){
            log.info("删除文件失败，文件路径为空");
            return false;
        }
        //获取文件
        String path = filePath.split("master/")[1];
        if(path == null || "".equals(path.trim())){
            log.info("删除文件失败，文件不存在");
            return false;
        }
        //设置请求路径
        String requestUrl = String.format(ImgMapConfig.GET_IMG_URL, ImgMapConfig.OWNER,
                ImgMapConfig.REPO_NAME, path);
        log.info("请求Gitee仓库路径:{}",requestUrl);
        //获取图片所有信息
        String resultJson = HttpUtil.get(requestUrl);

        JSONObject jsonObject = JSONUtil.parseObj(resultJson);
        if (jsonObject == null) {
            log.error("Gitee服务器未响应,message:{}",jsonObject);
            return false;
        }
        //获取sha,用于删除图片
        String sha = jsonObject.getStr("sha");
        //设置删除请求参数
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("access_token", ImgMapConfig.ACCESS_TOKEN);
        paramMap.put("sha", sha);
        paramMap.put("message", ImgMapConfig.DEl_MESSAGE);
        //设置删除路径
        requestUrl = String.format(ImgMapConfig.DEL_IMG_URL, ImgMapConfig.OWNER,
                ImgMapConfig.REPO_NAME, path);
        log.info("请求Gitee仓库路径:{}",requestUrl);
        //删除文件请求路径
        resultJson = HttpRequest.delete(requestUrl).form(paramMap).execute().body();
        HttpRequest.put(requestUrl).form(paramMap).execute().body();
        jsonObject = JSONUtil.parseObj(resultJson);
        //请求之后的操作
        if(jsonObject.getObj("commit") == null){
            log.error("Gitee服务器未响应,message:{}",jsonObject);
            return false;
        }
        return true;
    }
    /**
     * 下载文件
     * @Description:尚未想到怎么实现
     */
    public static void download(String url){


    }
}
